package cc.rengu.redp.bizimpl.upmp.service.impl;

import cc.rengu.igas.bomp.facade.BompMchntQueryService;
import cc.rengu.igas.bomp.facade.request.MchntSignInfoQueryRequest;
import cc.rengu.igas.bomp.facade.response.MchntBaseInfoQueryResponse;
import cc.rengu.igas.bomp.facade.response.MchntSignInfoQueryResponse;
import cc.rengu.redp.bizimpl.enums.*;
import cc.rengu.redp.bizimpl.igas.service.PDstChannelInfoService;
import cc.rengu.redp.bizimpl.upmp.common.BusinessContainer;
import cc.rengu.redp.bizimpl.upmp.dao.UpmpBMchntBlacklistInfoMapper;
import cc.rengu.redp.bizimpl.upmp.domain.*;
import cc.rengu.redp.bizimpl.upmp.service.*;
import cc.rengu.redp.bizimpl.upmp.vo.UpmpUserInfoVO;
import cc.rengu.redp.bizimpl.utils.Common;
import cc.rengu.redp.bizimpl.utils.CommonUtils;
import cc.rengu.redp.bizimpl.utils.DateUtils;
import cc.rengu.redp.bizimpl.utils.GZIPUtils;
import cc.rengu.redp.common.domain.QueryRequest;
import cc.rengu.redp.common.exception.RedpException;
import cc.rengu.redp.common.utils.SortUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 刘玉亮.LL
 * @since 2021-06-22
 */
@Service
@DS("upmp")
public class UpmpBMchntBlacklistInfoServiceImpl extends ServiceImpl<UpmpBMchntBlacklistInfoMapper, UpmpBMchntBlacklistInfo> implements IUpmpBMchntBlacklistInfoService {

    @Autowired
    private IUpmpSysParamService upmpSysParamService;
    @Autowired
    private IUpmpBMchntBaseInfoService bMchntBaseInfoService;

    @DubboReference(version = "${dubbo.protocol.version}", check = false)
//    @Autowired
    private BompMchntQueryService bompMchntQueryService;

    @Autowired
    private IUpmpBMchntSignInfoService bMchntSignInfoService;
    @Autowired
    private IUpmpOrganizationService organizationService;
    @Autowired
    private IUpmpPrivilegeCheckService authPrivilegeCheckService;
    @Autowired
    private IBizTmpService bizTmpService;
    @Autowired
    private IBizHisService bizHisService;
    @Autowired
    private PDstChannelInfoService pDstChannelInfoService;


    @Override
    public IPage<UpmpBMchntBlacklistInfo> findByPage(QueryRequest queryRequest, UpmpBMchntBlacklistInfo blacklistInfo) {
        //获取当前登录人信息
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        LambdaQueryWrapper<UpmpBMchntBlacklistInfo> queryWrapper = new LambdaQueryWrapper<>();

        if (null != user && user.isAdmin()) {

            if (!StringUtils.isEmpty(blacklistInfo.getInstId())) {
                queryWrapper.eq(UpmpBMchntBlacklistInfo::getInstId, blacklistInfo.getInstId());
            }
            if(!StringUtils.isEmpty(blacklistInfo.getMchntNo())){
                queryWrapper.eq(UpmpBMchntBlacklistInfo::getMchntNo, blacklistInfo.getMchntNo());
            }
            if (!StringUtils.isEmpty(blacklistInfo.getDataSources())) {
                queryWrapper.eq(UpmpBMchntBlacklistInfo::getDataSources, blacklistInfo.getDataSources());
            }

        } else {
            if (!StringUtils.isEmpty(blacklistInfo.getInstId())) {
                queryWrapper.and(i -> i.like(UpmpBMchntBlacklistInfo::getInstId, blacklistInfo.getInstId())
                        .or().like(UpmpBMchntBlacklistInfo::getCrtOrgId, GZIPUtils.uncompressToString(user.getUserOrgCodes()).split(",")));
            }

            if (!StringUtils.isEmpty(blacklistInfo.getMchntNo())) {
                queryWrapper.eq(UpmpBMchntBlacklistInfo::getMchntNo, blacklistInfo.getMchntNo());
            }
            if (!StringUtils.isEmpty(blacklistInfo.getDataSources())) {
                queryWrapper.eq(UpmpBMchntBlacklistInfo::getDataSources, blacklistInfo.getDataSources());
            }

        }

        try {
            Page<UpmpBMchntBlacklistInfo> page = new Page<>();
            SortUtil.handlePageSort(queryRequest, page, true);

            //设置模型数量
            Page<UpmpBMchntBlacklistInfo> infoPage = this.page(page, queryWrapper);
            return infoPage;
        } catch (Exception e) {
            log.error("获取商户黑名单信息失败", e);
            return null;
        }
    }

    @Override
    public UpmpBMchntBlacklistInfo initFormData(UpmpBMchntBlacklistInfo blacklistInfo) throws RedpException {
        //获取当前登录人信息
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        CommonUtils.validateUserInst(blacklistInfo.getInstId(), user);
        String id = blacklistInfo.getId();
        MchntBaseInfoQueryResponse resp = bMchntBaseInfoService.mchntBaseInfoQuery(blacklistInfo.getInstId(), user, bompMchntQueryService,
                bMchntBaseInfoService.genMerOrder(blacklistInfo.getInstId()), blacklistInfo.getMchntNo(), blacklistInfo.getMchntName(), BompQueryTypeEnum.REAL);
        if (Common.isNotBlank(resp)) {
            BeanUtils.copyProperties(resp.getMchntBaseInfo(), blacklistInfo);
            BeanUtils.copyProperties(resp.getMchntContactsInfo(), blacklistInfo);
            BeanUtils.copyProperties(resp, blacklistInfo);

            MchntSignInfoQueryRequest reqSign = new MchntSignInfoQueryRequest();
            reqSign.setMchntNo(blacklistInfo.getMchntNo());
            reqSign.setUserId(user.getId());
            MchntSignInfoQueryResponse respSign = bMchntSignInfoService.mchntSignInfoQuery(blacklistInfo.getInstId(), reqSign, bompMchntQueryService, bMchntBaseInfoService.genMerOrder(blacklistInfo.getInstId()), BompQueryTypeEnum.REAL);
            if (Common.isNotBlank(respSign)) {
                if (Common.isNotBlank(respSign)) {
                    BeanUtils.copyProperties(respSign.getMchntArtifInfo(), blacklistInfo);
                    BeanUtils.copyProperties(respSign.getBusinessLicenceInfo(), blacklistInfo);
                    blacklistInfo.setArtifCertType(respSign.getMchntArtifInfo().getArtifCertType());
                    blacklistInfo.setPostalAddress(respSign.getBusinessLicenceInfo().getRegisterStreet());
                    blacklistInfo.setLicenceExpireDate(respSign.getBusinessLicenceInfo().getLicenceExpiryDate());
                }
            }
            blacklistInfo.setId(id);
        }
        return blacklistInfo;
    }

    @Override
    public void updateMchntBlack(UpmpBMchntBlacklistInfo blacklistInfo) throws RedpException {
        saveData(blacklistInfo);
    }

    @Override
    public void addMchntBlack(UpmpBMchntBlacklistInfo blacklistInfo) throws RedpException {
        saveData(blacklistInfo);
    }

    private void saveData(UpmpBMchntBlacklistInfo entity) throws RedpException {
        String flag = entity.getOptFlag();
        String lastUpddt = DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss.SSS");
        //获取当前登录人信息
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        UpmpOrganization org = organizationService.getOrgByCode(user.getOrgCode(), user.getInstId());

        if (PageOptFlagEnum.OPT_FLAG_ADD.getType().equals(flag)) {
            UpmpPrivilegeCheck privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(entity.getInstId(), "商户黑名单管理:新增");
            //
            entity.setId(null);
            entity.setOprId(user.getId());
            entity.setCreateTime(lastUpddt);
            entity.setLastOprId(user.getId());
            entity.setLastUpdateTime(lastUpddt);
            //
            if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                entity.setMchntBlacklistStatus(BizDataStatusEnum.STATUS_DRAFT.getType());
                entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_CHECKING.getType());
                this.save(entity);

                bizTmpService.saveBizTmp(entity, user, user.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt,
                        String.valueOf(pDstChannelInfoService.getOprMenuId()), pDstChannelInfoService.getOprMenuName(),
                        entity.getMchntBlacklistStatus(), entity.getAuditStatus(), entity.getId(), "", null, null, null);

            } else {
                entity.setMchntBlacklistStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
                entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_PASS.getType());
                this.save(entity);

                bizHisService.saveBizHisNew(entity, entity, user, user.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt,
                        String.valueOf(pDstChannelInfoService.getOprMenuId()), pDstChannelInfoService.getOprMenuName(),
                        entity.getId(), null, null, null);

            }
        } else if (PageOptFlagEnum.OPT_FLAG_UPDATE.getType().equals(flag)) {
            String id = entity.getId();
            if (Common.isBlank(id)) {
                log.error("请求参数(id)异常!");
                throw new RedpException("请求参数(id)异常!");
            }

            UpmpPrivilegeCheck privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(entity.getInstId(), "商户黑名单管理:新增");
            UpmpBMchntBlacklistInfo dbMchntBlackListInfo = baseMapper.selectById(id);
            UpmpBMchntBlacklistInfo mchntBlackListInfo = new UpmpBMchntBlacklistInfo();
            BeanUtils.copyProperties(entity, mchntBlackListInfo);

            entity.setLastOprId(user.getId());
            entity.setLastUpdateTime(lastUpddt);
            entity.setMchntBlacklistStatus(dbMchntBlackListInfo.getMchntBlacklistStatus());
            if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                dbMchntBlackListInfo.setLastOprId(user.getId());
                dbMchntBlackListInfo.setLastUpdateTime(lastUpddt);
                dbMchntBlackListInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_CHECKING.getType());

                this.updateById(dbMchntBlackListInfo);

                //检查临时表是否有数据，如果没用则新增
                entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_CHECKING.getType());
                BeanUtils.copyProperties(entity, dbMchntBlackListInfo);

                bizTmpService.saveBizTmp(dbMchntBlackListInfo, user, user.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt,
                        String.valueOf(pDstChannelInfoService.getOprMenuId()), pDstChannelInfoService.getOprMenuName(),
                        dbMchntBlackListInfo.getMchntBlacklistStatus(), dbMchntBlackListInfo.getAuditStatus(), dbMchntBlackListInfo.getId(), "", null, null, null);

            } else {
                entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_PASS.getType());

                BeanUtils.copyProperties(entity, mchntBlackListInfo);
                this.updateById(mchntBlackListInfo);

                //历史表新增
                bizHisService.saveBizHisNew(mchntBlackListInfo, dbMchntBlackListInfo, user, user.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt,
                        String.valueOf(pDstChannelInfoService.getOprMenuId()), pDstChannelInfoService.getOprMenuName(),
                        mchntBlackListInfo.getId(), null, null, null);
            }
        } else if (PageOptFlagEnum.OPT_FLAG_STOP.getType().equals(flag)
                || PageOptFlagEnum.OPT_FLAG_USE.getType().equals(flag)
                || PageOptFlagEnum.OPT_FLAG_CANCEL.getType().equals(flag)) {
            String id = entity.getId();
            if (Common.isBlank(id)) {
                log.error("请求参数(id)异常!");
                throw new RedpException("请求参数(id)异常!");
            }
            UpmpBMchntBlacklistInfo mchntBlackListInfo = baseMapper.selectById(id);

            if (Common.isBlank(mchntBlackListInfo)) {
                log.error("根据id没有找到指定数据！");
                throw new RedpException("根据id没有找到指定数据！");
            }
            UpmpPrivilegeCheck privilegeCheck = new UpmpPrivilegeCheck();
            String bizOpr = "";
            if (PageOptFlagEnum.OPT_FLAG_STOP.getType().equals(flag)) {
                bizOpr = BizOprEnum.OPR_STOP.getType();
                privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(user.getInstId(), "商户黑名单管理:停用");
                if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                    mchntBlackListInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_STOP_CHECKING.getType());
                } else {
                    mchntBlackListInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_STOP_PASS.getType());
                }
            } else if (PageOptFlagEnum.OPT_FLAG_USE.getType().equals(flag)) {

                bizOpr = BizOprEnum.OPR_USE.getType();
                privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(user.getInstId(), "商户黑名单管理:启用");
                if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                    mchntBlackListInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_USE_CHECKING.getType());
                } else {
                    mchntBlackListInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_USE_PASS.getType());
                }
            } else if (PageOptFlagEnum.OPT_FLAG_CANCEL.getType().equals(flag)) {

                bizOpr = BizOprEnum.OPR_CANCEL.getType();
                privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(user.getInstId(), "商户黑名单管理:注销");
                if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                    mchntBlackListInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_CANCEL_CHECKING.getType());
                } else {
                    mchntBlackListInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_CANCEL_PASS.getType());
                }
            }
            mchntBlackListInfo.setLastOprId(user.getId());
            mchntBlackListInfo.setMchntBlacklistStatus(BizDataStatusEnum.STATUS_CANCELED.getType());
            mchntBlackListInfo.setLastUpdateTime(lastUpddt);
            this.updateById(mchntBlackListInfo);

            if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                //检查临时表是否有数据，如果没用则新增
                bizTmpService.saveBizTmp(mchntBlackListInfo, user, user.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt,
                        String.valueOf(pDstChannelInfoService.getOprMenuId()), pDstChannelInfoService.getOprMenuName(),
                        mchntBlackListInfo.getMchntBlacklistStatus(), mchntBlackListInfo.getAuditStatus(), mchntBlackListInfo.getId(), "", null, null, null);
            } else {
                //历史表新增
                bizHisService.saveBizHisNew(entity, mchntBlackListInfo, user, user.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt,
                        String.valueOf(pDstChannelInfoService.getOprMenuId()), pDstChannelInfoService.getOprMenuName(),
                        mchntBlackListInfo.getId(), null, null, null);
            }
        } else if (PageOptFlagEnum.OPT_FLAG_CHECK.getType().equals(flag)) {

            String id = entity.getId();
            if (Common.isBlank(id)) {
                log.error("请求参数(id)异常!");
                throw new RedpException("请求参数(id)异常!");
            }

            //获取临时表数据并转换成实体对象
            BizTmp tmp = bizTmpService.getById(id);
            if (Common.isBlank(tmp)) {
                log.error("根据id没有找到指定临时表数据！");
                throw new RedpException("根据id没有找到指定临时表数据！");
            }
            String bizdata = "";
            if (null != tmp.getBizData1()) {
                bizdata += tmp.getBizData1();
            }
            if (null != tmp.getBizData2()) {
                bizdata += tmp.getBizData2();
            }
            if (null != tmp.getBizData3()) {
                bizdata += tmp.getBizData3();
            }
            // 临时表数据
            UpmpBMchntBlacklistInfo mchntBlackListInfoNew = JSON.parseObject(bizdata, UpmpBMchntBlacklistInfo.class);
            // 正式表数据
            UpmpBMchntBlacklistInfo mchntBlackListInfo = baseMapper.selectById(id);
            // 备份正式表数据
            UpmpBMchntBlacklistInfo mchntBlackListInfoOld = new UpmpBMchntBlacklistInfo();
            BeanUtils.copyProperties(mchntBlackListInfo, mchntBlackListInfoOld);
            //
            if (Common.isBlank(mchntBlackListInfo) && !BizOprEnum.OPR_ADD.equals(tmp.getBizOpr())) {
                log.error("根据id没有找到指定数据！");
                throw new RedpException("根据id没有找到指定数据！");
            }

            String opt = entity.getOpt();
            if (Common.isBlank(opt)) {
                log.error("请求参数(opt)异常!");
                throw new RedpException("请求参数(opt)异常!");
            }
            //
            if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                // 审批通过将临时表数据更新到正式表
                BeanUtils.copyProperties(mchntBlackListInfoNew, mchntBlackListInfo);
            } else {
                String auditRefuseReason = entity.getAuditRefuseReason();
                mchntBlackListInfo.setAuditRefuseReason(auditRefuseReason);
            }
            String bizOpr = "";
            if (BizDataAuditStatusEnum.AUDIT_STATUS_ADD_CHECKING.getType().equals(mchntBlackListInfo.getAuditStatus())) {
                if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                    mchntBlackListInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_PASS.getType());
                    mchntBlackListInfo.setMchntBlacklistStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
                } else {
                    mchntBlackListInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_REJECT.getType());
                }
                bizOpr = BizOprEnum.OPR_ADD.getType();
            } else if (BizDataAuditStatusEnum.AUDIT_STATUS_CANCEL_CHECKING.getType().equals(mchntBlackListInfo.getAuditStatus())) {
                if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                    mchntBlackListInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_CANCEL_PASS.getType());
                    mchntBlackListInfo.setMchntBlacklistStatus(BizDataStatusEnum.STATUS_CANCELED.getType());
                } else {
                    mchntBlackListInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_CANCEL_REJECT.getType());
                }
                bizOpr = BizOprEnum.OPR_CANCEL.getType();
            } else if (BizDataAuditStatusEnum.AUDIT_STATUS_STOP_CHECKING.getType().equals(mchntBlackListInfo.getAuditStatus())) {
                if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                    mchntBlackListInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_STOP_PASS.getType());
                    mchntBlackListInfo.setMchntBlacklistStatus(BizDataStatusEnum.STATUS_STOPED.getType());
                } else {
                    mchntBlackListInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_STOP_REJECT.getType());
                }
                bizOpr = BizOprEnum.OPR_STOP.getType();
            } else if (BizDataAuditStatusEnum.AUDIT_STATUS_USE_CHECKING.getType().equals(mchntBlackListInfo.getAuditStatus())) {
                if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                    mchntBlackListInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_USE_PASS.getType());
                    mchntBlackListInfo.setMchntBlacklistStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
                } else {
                    mchntBlackListInfo.setMchntBlacklistStatus(BizDataAuditStatusEnum.AUDIT_STATUS_USE_REJECT.getType());
                }
                bizOpr = BizOprEnum.OPR_USE.getType();
            } else if (BizDataAuditStatusEnum.AUDIT_STATUS_UPD_CHECKING.getType().equals(mchntBlackListInfo.getAuditStatus())) {
                if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                    mchntBlackListInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_PASS.getType());
                    mchntBlackListInfo.setMchntBlacklistStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
                } else {
                    mchntBlackListInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_REJECT.getType());
                }
                bizOpr = BizOprEnum.OPR_UPDATE.getType();
            }
            // 状态赋值完成后，入库正式表
            this.updateById(mchntBlackListInfo);
            //
            if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                //审批通过将正式表更新到历史表
                bizHisService.saveBizHisNew(mchntBlackListInfo, mchntBlackListInfoOld, user, user.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt,
                        String.valueOf(pDstChannelInfoService.getOprMenuId()), pDstChannelInfoService.getOprMenuName(),
                        mchntBlackListInfo.getId(), null, null, null);

            }
            // 修改临时表的审核状态等字段
            bizTmpService.saveBizTmp(mchntBlackListInfo, user, user.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt,
                    String.valueOf(pDstChannelInfoService.getOprMenuId()), pDstChannelInfoService.getOprMenuName(),
                    mchntBlackListInfo.getMchntBlacklistStatus(), mchntBlackListInfo.getAuditStatus(), mchntBlackListInfo.getId(), "", null, null, null);

        }

    }


}
